<template>
  <div class="rules-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-nav">
        <div class="nav-left">
          <!-- <a-button type="text" @click="goBack" class="back-btn">
            <ArrowLeftOutlined />
            <span>返回</span>
          </a-button> -->

          <div class="breadcrumb">
            <router-link to="/dashboard" class="breadcrumb-item">
              <HomeOutlined />
              <span>工作台</span>
            </router-link>
            <span class="breadcrumb-separator">/</span>
            <router-link to="/reincarnation" class="breadcrumb-item">轮回转世系统</router-link>
            <span class="breadcrumb-separator">/</span>
            <span class="breadcrumb-item current">转世规则管理</span>
          </div>
        </div>
      </div>

      <div class="header-content">
        <div class="header-main">
          <h1 class="page-title">转世规则管理</h1>
          <p class="page-description">六道轮回规则 · 业力等级对应 · 转世条件设置</p>
        </div>

        <div class="header-actions">
          <a-dropdown>
            <a-button type="primary">
              <PlusOutlined />
              新增规则
            </a-button>
            <template #overlay>
              <a-menu>
                <a-menu-item @click="addRealmRule">
                  <GlobalOutlined />
                  六道轮回规则
                </a-menu-item>
                <a-menu-item @click="addCondition">
                  <SettingOutlined />
                  转世条件规则
                </a-menu-item>
                <a-menu-item @click="addKarmaLevel">
                  <TrophyOutlined />
                  业力等级规则
                </a-menu-item>
                <a-menu-item @click="addSpecialApplication">
                  <StarOutlined />
                  特殊转世申请
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
          <a-button @click="exportRules">
            <ExportOutlined />
            导出规则
          </a-button>
        </div>
      </div>
    </div>

    <!-- 功能导航卡片 -->
    <div class="function-nav">
      <a-row :gutter="[24, 24]">
        <a-col :xs="24" :sm="12" :lg="6">
          <div class="nav-card" :class="{ active: activeTab === 'realms' }" @click="activeTab = 'realms'">
            <div class="nav-icon realms">
              <GlobalOutlined />
            </div>
            <div class="nav-content">
              <div class="nav-title">六道轮回规则</div>
              <div class="nav-count">{{ realmRules.length }} 项规则</div>
            </div>
          </div>
        </a-col>

        <a-col :xs="24" :sm="12" :lg="6">
          <div class="nav-card" :class="{ active: activeTab === 'conditions' }" @click="activeTab = 'conditions'">
            <div class="nav-icon conditions">
              <SettingOutlined />
            </div>
            <div class="nav-content">
              <div class="nav-title">转世条件设置</div>
              <div class="nav-count">{{ conditionRules.length }} 项条件</div>
            </div>
          </div>
        </a-col>

        <a-col :xs="24" :sm="12" :lg="6">
          <div class="nav-card" :class="{ active: activeTab === 'karma' }" @click="activeTab = 'karma'">
            <div class="nav-icon karma">
              <TrophyOutlined />
            </div>
            <div class="nav-content">
              <div class="nav-title">业力等级对应</div>
              <div class="nav-count">{{ karmaLevels.length }} 个等级</div>
            </div>
          </div>
        </a-col>

        <a-col :xs="24" :sm="12" :lg="6">
          <div class="nav-card" :class="{ active: activeTab === 'special' }" @click="activeTab = 'special'">
            <div class="nav-icon special">
              <StarOutlined />
            </div>
            <div class="nav-content">
              <div class="nav-title">特殊转世申请</div>
              <div class="nav-count">{{ specialApplications.length }} 项申请</div>
            </div>
          </div>
        </a-col>
      </a-row>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 六道轮回规则 -->
      <div v-if="activeTab === 'realms'" class="content-section">
        <div class="section-header">
          <h3>六道轮回规则</h3>
          <a-button type="primary" size="small" @click="addRealmRule"> 添加规则 </a-button>
        </div>

        <div class="realm-rules-grid">
          <div v-for="rule in realmRules" :key="rule.id" class="realm-rule-card">
            <div class="rule-header">
              <div class="realm-info">
                <div class="realm-icon" :style="{ backgroundColor: rule.color }">
                  {{ rule.icon }}
                </div>
                <div class="realm-details">
                  <div class="realm-name">{{ rule.realm }}</div>
                  <div class="realm-type">{{ rule.type }}</div>
                </div>
              </div>
              <div class="rule-actions">
                <a-switch v-model:checked="rule.enabled" size="small" @change="toggleRule(rule)" />
                <a-dropdown>
                  <a-button type="text" size="small">
                    <MoreOutlined />
                  </a-button>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item @click="editRule(rule)">
                        <EditOutlined />
                        编辑规则
                      </a-menu-item>
                      <a-menu-item @click="copyRule(rule)">
                        <CopyOutlined />
                        复制规则
                      </a-menu-item>
                      <a-menu-divider />
                      <a-menu-item @click="deleteRule(rule)" danger>
                        <DeleteOutlined />
                        删除规则
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </div>
            </div>

            <div class="rule-content">
              <div class="rule-description">{{ rule.description }}</div>
              <div class="rule-conditions">
                <div class="condition-item">
                  <span class="condition-label">业力范围：</span>
                  <span class="condition-value">{{ rule.karmaRange }}</span>
                </div>
                <div class="condition-item">
                  <span class="condition-label">前世要求：</span>
                  <span class="condition-value">{{ rule.previousLife }}</span>
                </div>
                <div class="condition-item">
                  <span class="condition-label">特殊条件：</span>
                  <span class="condition-value">{{ rule.specialCondition || '无' }}</span>
                </div>
              </div>
            </div>

            <div class="rule-footer">
              <div class="rule-stats">
                <span class="stat-item">
                  <span class="stat-label">应用次数：</span>
                  <span class="stat-value">{{ rule.usageCount }}</span>
                </span>
                <span class="stat-item">
                  <span class="stat-label">成功率：</span>
                  <span class="stat-value success">{{ rule.successRate }}%</span>
                </span>
              </div>
              <div class="rule-time">更新于 {{ rule.updateTime }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 转世条件设置 -->
      <div v-if="activeTab === 'conditions'" class="content-section">
        <div class="section-header">
          <h3>转世条件设置</h3>
          <a-button type="primary" size="small" @click="addCondition"> 添加条件 </a-button>
        </div>

        <div class="conditions-list">
          <div v-for="condition in conditionRules" :key="condition.id" class="condition-card">
            <div class="condition-header">
              <div class="condition-info">
                <div class="condition-name">{{ condition.name }}</div>
                <div class="condition-category">{{ condition.category }}</div>
              </div>
              <div class="condition-actions">
                <a-tag :color="condition.priority === '高' ? 'red' : condition.priority === '中' ? 'orange' : 'blue'"> {{ condition.priority }}优先级 </a-tag>
                <a-switch v-model:checked="condition.enabled" size="small" />
              </div>
            </div>

            <div class="condition-content">
              <div class="condition-description">{{ condition.description }}</div>
              <div class="condition-details">
                <div class="detail-row">
                  <span class="detail-label">触发条件：</span>
                  <span class="detail-value">{{ condition.trigger }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">执行动作：</span>
                  <span class="detail-value">{{ condition.action }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">影响范围：</span>
                  <span class="detail-value">{{ condition.scope }}</span>
                </div>
              </div>
            </div>

            <div class="condition-footer">
              <div class="condition-stats">触发次数：{{ condition.triggerCount }} | 成功率：{{ condition.successRate }}%</div>
              <div class="condition-actions">
                <a-button type="text" size="small" @click="editCondition(condition)"> 编辑 </a-button>
                <a-button type="text" size="small" @click="testCondition(condition)"> 测试 </a-button>
                <a-button type="text" size="small" danger @click="deleteCondition(condition)"> 删除 </a-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 业力等级对应 -->
      <div v-if="activeTab === 'karma'" class="content-section">
        <div class="section-header">
          <h3>业力等级对应表</h3>
          <a-button type="primary" size="small" @click="addKarmaLevel"> 添加等级 </a-button>
        </div>

        <div class="karma-levels-table">
          <a-table :columns="karmaColumns" :data-source="karmaLevels" :pagination="false" size="middle">
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'level'">
                <div class="karma-level">
                  <div class="level-badge" :style="{ backgroundColor: record.color }">
                    {{ record.level }}
                  </div>
                  <div class="level-name">{{ record.name }}</div>
                </div>
              </template>

              <template v-if="column.dataIndex === 'range'">
                <div class="karma-range">
                  <div class="range-bar">
                    <div
                      class="range-fill"
                      :style="{
                        width: record.max / 100 + '%',
                        backgroundColor: record.color
                      }"
                    ></div>
                  </div>
                  <div class="range-text">{{ record.min }} - {{ record.max }}</div>
                </div>
              </template>

              <template v-if="column.dataIndex === 'realmAccess'">
                <div class="realm-access">
                  <a-tag v-for="realm in record.realmAccess" :key="realm" size="small" :color="getRealmColor(realm)">
                    {{ realm }}
                  </a-tag>
                </div>
              </template>

              <template v-if="column.dataIndex === 'actions'">
                <a-space>
                  <a-button type="text" size="small" @click="editKarmaLevel(record)"> 编辑 </a-button>
                  <a-button type="text" size="small" danger @click="deleteKarmaLevel(record)"> 删除 </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </div>
      </div>

      <!-- 特殊转世申请 -->
      <div v-if="activeTab === 'special'" class="content-section">
        <div class="section-header">
          <h3>特殊转世申请</h3>
          <a-space>
            <a-select v-model:value="specialFilter" style="width: 120px" size="small" placeholder="筛选状态">
              <a-select-option value="">全部</a-select-option>
              <a-select-option value="pending">待审</a-select-option>
              <a-select-option value="approved">已批准</a-select-option>
              <a-select-option value="rejected">已拒绝</a-select-option>
            </a-select>
            <a-button type="primary" size="small" @click="addSpecialApplication"> 新增申请 </a-button>
          </a-space>
        </div>

        <div class="special-applications-list">
          <div v-for="application in filteredSpecialApplications" :key="application.id" class="application-card">
            <div class="application-header">
              <div class="application-info">
                <div class="applicant-name">{{ application.applicantName }}</div>
                <div class="application-type">{{ application.type }}</div>
              </div>
              <div class="application-status">
                <a-tag :color="getStatusColor(application.status)">
                  {{ getStatusText(application.status) }}
                </a-tag>
                <div class="application-time">{{ application.submitTime }}</div>
              </div>
            </div>

            <div class="application-content">
              <div class="application-reason"><strong>申请原因：</strong>{{ application.reason }}</div>
              <div class="application-details">
                <div class="detail-grid">
                  <div class="detail-item">
                    <span class="detail-label">当前业力：</span>
                    <span class="detail-value">{{ application.currentKarma }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">目标道别：</span>
                    <span class="detail-value">{{ application.targetRealm }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">申请人身份：</span>
                    <span class="detail-value">{{ application.applicantRole }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">紧急程度：</span>
                    <span class="detail-value">{{ application.urgency }}</span>
                  </div>
                </div>
              </div>

              <div v-if="application.reviewComment" class="review-comment"><strong>审批意见：</strong>{{ application.reviewComment }}</div>
            </div>

            <div class="application-actions">
              <a-space>
                <a-button v-if="application.status === 'pending'" type="primary" size="small" @click="approveApplication(application)"> 批准 </a-button>
                <a-button v-if="application.status === 'pending'" danger size="small" @click="rejectApplication(application)"> 拒绝 </a-button>
                <a-button type="text" size="small" @click="editSpecialApplication(application)"> 编辑 </a-button>
                <a-button type="text" size="small" @click="viewApplicationDetail(application)"> 查看详情 </a-button>
                <a-button type="text" size="small" danger @click="deleteSpecialApplication(application)"> 删除 </a-button>
              </a-space>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 六道轮回规则添加/编辑弹窗 -->
    <a-modal v-model:visible="showRealmRuleModal" :title="editingRealmRule.id ? '编辑规则' : '新增规则'" width="800px" @ok="saveRealmRule" @cancel="cancelRealmRule">
      <a-form :model="editingRealmRule" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="道别名称" required>
          <a-input v-model:value="editingRealmRule.realm" placeholder="请输入道别名称" />
        </a-form-item>
        <a-form-item label="道别类型" required>
          <a-select v-model:value="editingRealmRule.type" placeholder="请选择道别类型">
            <a-select-option value="善道">善道</a-select-option>
            <a-select-option value="恶道">恶道</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="图标">
          <a-input v-model:value="editingRealmRule.icon" placeholder="请输入图标" />
        </a-form-item>
        <a-form-item label="颜色">
          <a-input v-model:value="editingRealmRule.color" placeholder="请输入颜色代码" />
        </a-form-item>
        <a-form-item label="业力范围" required>
          <a-input v-model:value="editingRealmRule.karmaRange" placeholder="如：90-100" />
        </a-form-item>
        <a-form-item label="前世要求">
          <a-input v-model:value="editingRealmRule.previousLife" placeholder="请输入前世要求" />
        </a-form-item>
        <a-form-item label="特殊条件">
          <a-input v-model:value="editingRealmRule.specialCondition" placeholder="请输入特殊条件" />
        </a-form-item>
        <a-form-item label="规则描述" required>
          <a-textarea v-model:value="editingRealmRule.description" :rows="3" placeholder="请输入规则描述" />
        </a-form-item>
        <a-form-item label="详细规则">
          <a-textarea v-model:value="detailedRulesText" :rows="4" placeholder="每行一条规则，自动转换为数组" />
        </a-form-item>
        <a-form-item label="限制条件">
          <a-textarea v-model:value="restrictionsText" :rows="3" placeholder="每行一条限制，自动转换为数组" />
        </a-form-item>
        <a-form-item label="道别益处">
          <a-textarea v-model:value="benefitsText" :rows="3" placeholder="每行一条益处，自动转换为数组" />
        </a-form-item>
        <a-form-item label="创建者">
          <a-input v-model:value="editingRealmRule.creator" placeholder="请输入创建者" />
        </a-form-item>
        <a-form-item label="状态">
          <a-switch v-model:checked="editingRealmRule.enabled" checked-children="启用" un-checked-children="禁用" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 转世条件添加/编辑弹窗 -->
    <a-modal v-model:visible="showConditionModal" :title="editingCondition.id ? '编辑条件' : '新增条件'" width="800px" @ok="saveCondition" @cancel="cancelCondition">
      <a-form :model="editingCondition" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="条件名称" required>
          <a-input v-model:value="editingCondition.name" placeholder="请输入条件名称" />
        </a-form-item>
        <a-form-item label="条件分类" required>
          <a-select v-model:value="editingCondition.category" placeholder="请选择条件分类">
            <a-select-option value="基础条件">基础条件</a-select-option>
            <a-select-option value="因果条件">因果条件</a-select-option>
            <a-select-option value="特殊条件">特殊条件</a-select-option>
            <a-select-option value="净化条件">净化条件</a-select-option>
            <a-select-option value="血脉条件">血脉条件</a-select-option>
            <a-select-option value="环境条件">环境条件</a-select-option>
            <a-select-option value="时机条件">时机条件</a-select-option>
            <a-select-option value="关系条件">关系条件</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="优先级" required>
          <a-select v-model:value="editingCondition.priority" placeholder="请选择优先级">
            <a-select-option value="高">高</a-select-option>
            <a-select-option value="中">中</a-select-option>
            <a-select-option value="低">低</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="适用范围" required>
          <a-input v-model:value="editingCondition.scope" placeholder="如：所有道别、善道转世等" />
        </a-form-item>
        <a-form-item label="触发条件" required>
          <a-input v-model:value="editingCondition.trigger" placeholder="请输入触发条件" />
        </a-form-item>
        <a-form-item label="执行动作" required>
          <a-input v-model:value="editingCondition.action" placeholder="请输入执行动作" />
        </a-form-item>
        <a-form-item label="条件描述" required>
          <a-textarea v-model:value="editingCondition.description" :rows="3" placeholder="请输入条件描述" />
        </a-form-item>
        <a-form-item label="详细说明">
          <a-textarea v-model:value="editingCondition.detailDescription" :rows="4" placeholder="请输入详细说明" />
        </a-form-item>
        <a-form-item label="检查要点">
          <a-textarea v-model:value="checkPointsText" :rows="3" placeholder="每行一个要点，自动转换为数组" />
        </a-form-item>
        <a-form-item label="例外情况">
          <a-textarea v-model:value="exceptionsText" :rows="3" placeholder="每行一种例外，自动转换为数组" />
        </a-form-item>
        <a-form-item label="创建者">
          <a-input v-model:value="editingCondition.creator" placeholder="请输入创建者" />
        </a-form-item>
        <a-form-item label="状态">
          <a-switch v-model:checked="editingCondition.enabled" checked-children="启用" un-checked-children="禁用" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 业力等级添加/编辑弹窗 -->
    <a-modal v-model:visible="showKarmaModal" :title="editingKarma.id ? '编辑等级' : '新增等级'" width="600px" @ok="saveKarma" @cancel="cancelKarma">
      <a-form :model="editingKarma" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="等级代号" required>
          <a-input v-model:value="editingKarma.level" placeholder="如：S、A+、A等" />
        </a-form-item>
        <a-form-item label="等级名称" required>
          <a-input v-model:value="editingKarma.name" placeholder="如：圣者级、大善级等" />
        </a-form-item>
        <a-form-item label="最小值" required>
          <a-input-number v-model:value="editingKarma.min" :min="0" :max="100" placeholder="最小业力值" style="width: 100%" />
        </a-form-item>
        <a-form-item label="最大值" required>
          <a-input-number v-model:value="editingKarma.max" :min="0" :max="100" placeholder="最大业力值" style="width: 100%" />
        </a-form-item>
        <a-form-item label="标识颜色">
          <a-input v-model:value="editingKarma.color" placeholder="请输入颜色代码" />
        </a-form-item>
        <a-form-item label="可转世道别">
          <a-textarea v-model:value="realmAccessText" :rows="2" placeholder="每行一个道别，自动转换为数组" />
        </a-form-item>
        <a-form-item label="等级描述" required>
          <a-textarea v-model:value="editingKarma.description" :rows="3" placeholder="请输入等级描述" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 特殊申请添加/编辑弹窗 -->
    <a-modal v-model:visible="showSpecialModal" :title="editingSpecial.id ? '编辑申请' : '新增申请'" width="900px" @ok="saveSpecial" @cancel="cancelSpecial">
      <a-form :model="editingSpecial" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="申请人姓名" required>
          <a-input v-model:value="editingSpecial.applicantName" placeholder="请输入申请人姓名" />
        </a-form-item>
        <a-form-item label="申请类型" required>
          <a-select v-model:value="editingSpecial.type" placeholder="请选择申请类型">
            <a-select-option value="紧急转世">紧急转世</a-select-option>
            <a-select-option value="特殊功德">特殊功德</a-select-option>
            <a-select-option value="业力争议">业力争议</a-select-option>
            <a-select-option value="菩萨推荐">菩萨推荐</a-select-option>
            <a-select-option value="因果债务">因果债务</a-select-option>
            <a-select-option value="修行成就">修行成就</a-select-option>
            <a-select-option value="特殊使命">特殊使命</a-select-option>
            <a-select-option value="冤屈申诉">冤屈申诉</a-select-option>
            <a-select-option value="亲情牵挂">亲情牵挂</a-select-option>
            <a-select-option value="业力超标">业力超标</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="当前业力" required>
          <a-input-number v-model:value="editingSpecial.currentKarma" :min="0" :max="100" placeholder="当前业力值" style="width: 100%" />
        </a-form-item>
        <a-form-item label="目标道别" required>
          <a-select v-model:value="editingSpecial.targetRealm" placeholder="请选择目标道别">
            <a-select-option value="天道">天道</a-select-option>
            <a-select-option value="人道">人道</a-select-option>
            <a-select-option value="阿修罗道">阿修罗道</a-select-option>
            <a-select-option value="畜生道">畜生道</a-select-option>
            <a-select-option value="饿鬼道">饿鬼道</a-select-option>
            <a-select-option value="地狱道">地狱道</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="申请人身份">
          <a-input v-model:value="editingSpecial.applicantRole" placeholder="请输入申请人身份" />
        </a-form-item>
        <a-form-item label="紧急程度" required>
          <a-select v-model:value="editingSpecial.urgency" placeholder="请选择紧急程度">
            <a-select-option value="紧急">紧急</a-select-option>
            <a-select-option value="普通">普通</a-select-option>
            <a-select-option value="低">低</a-select-option>
            <a-select-option value="机密">机密</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="前世身份">
          <a-input v-model:value="editingSpecial.previousLife" placeholder="请输入前世身份" />
        </a-form-item>
        <a-form-item label="死亡原因">
          <a-input v-model:value="editingSpecial.deathCause" placeholder="请输入死亡原因" />
        </a-form-item>
        <a-form-item label="申请原因" required>
          <a-textarea v-model:value="editingSpecial.reason" :rows="4" placeholder="请详细说明申请原因" />
        </a-form-item>
        <a-form-item label="善行记录">
          <a-textarea v-model:value="goodDeedsText" :rows="3" placeholder="每行一项善行，自动转换为数组" />
        </a-form-item>
        <a-form-item label="附件材料">
          <a-textarea v-model:value="attachmentsText" :rows="3" placeholder="每行一项附件，自动转换为数组" />
        </a-form-item>
        <a-form-item label="申请状态" required>
          <a-select v-model:value="editingSpecial.status" placeholder="请选择申请状态">
            <a-select-option value="pending">待审</a-select-option>
            <a-select-option value="approved">已批准</a-select-option>
            <a-select-option value="rejected">已拒绝</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="审批人">
          <a-input v-model:value="editingSpecial.reviewer" placeholder="请输入审批人" />
        </a-form-item>
        <a-form-item label="审批意见">
          <a-textarea v-model:value="editingSpecial.reviewComment" :rows="3" placeholder="请输入审批意见" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 删除确认弹窗 -->
    <a-modal v-model:visible="showDeleteModal" title="确认删除" @ok="confirmDelete" @cancel="cancelDelete">
      <p>确定要删除{{ deleteTarget.type }}："{{ deleteTarget.name }}"吗？</p>
      <p style="color: #ff4d4f; font-size: 12px">此操作不可恢复，请谨慎操作。</p>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { PlusOutlined, ExportOutlined, GlobalOutlined, SettingOutlined, TrophyOutlined, StarOutlined, MoreOutlined, EditOutlined, CopyOutlined, DeleteOutlined, ArrowLeftOutlined, HomeOutlined, DownOutlined } from '@ant-design/icons-vue'

// 路由
const router = useRouter()

// 当前活跃标签
const activeTab = ref('realms')

// 弹窗状态
const showAddRuleModal = ref(false)
const showRealmRuleModal = ref(false)
const showConditionModal = ref(false)
const showKarmaModal = ref(false)
const showSpecialModal = ref(false)
const showDeleteModal = ref(false)

// 特殊申请筛选
const specialFilter = ref('')

// 编辑中的数据
const editingRealmRule = ref({})
const editingCondition = ref({})
const editingKarma = ref({})
const editingSpecial = ref({})

// 删除目标
const deleteTarget = ref({ type: '', name: '', id: '', category: '' })

// 表单辅助文本（用于数组转换）
const detailedRulesText = ref('')
const restrictionsText = ref('')
const benefitsText = ref('')
const checkPointsText = ref('')
const exceptionsText = ref('')
const realmAccessText = ref('')
const goodDeedsText = ref('')
const attachmentsText = ref('')

// 六道轮回规则数据
const realmRules = ref([
  {
    id: 1,
    realm: '天道',
    type: '善道',
    icon: '☆',
    color: '#f59e0b',
    description: '天道是六道中最为殊胜的道别，需要极高的业力积累和善行功德。',
    karmaRange: '90-100',
    previousLife: '人道或天道',
    specialCondition: '需有大功德或修行成就',
    enabled: true,
    usageCount: 156,
    successRate: 95.2,
    updateTime: '2023-12-15 14:30',
    detailedRules: ['业力值需达到90分以上', '前世必须为人道或天道', '需要证明具有大功德或修行成就', '通过天道转世考核', '无重大恶业记录'],
    restrictions: ['不得有杀业', '不得有偷盗', '不得有邪淫', '不得有妄语', '不得有饮酒'],
    benefits: ['享受天界福报', '寿命极长', '智慧超群', '无病无痛', '具备神通'],
    creator: '玉皇大帝',
    lastModifier: '太上老君'
  },
  {
    id: 2,
    realm: '人道',
    type: '善道',
    icon: '♂',
    color: '#10b981',
    description: '人道是修行的最佳道别，有机会通过修行提升业力等级。',
    karmaRange: '60-89',
    previousLife: '不限',
    specialCondition: '无特殊要求',
    enabled: true,
    usageCount: 2456,
    successRate: 87.6,
    updateTime: '2023-12-15 10:15',
    detailedRules: ['业力值需达到60-89分', '前世道别不限', '具备基本善心', '无重大恶业', '通过基础转世审查'],
    restrictions: ['不得故意杀害无辜', '不得偷盗他人财物', '不得恶意诽谤他人'],
    benefits: ['具备修行机会', '可积累功德', '享受人间情感', '拥有自由意志', '可上升至更高道别'],
    creator: '观音菩萨',
    lastModifier: '地藏王菩萨'
  },
  {
    id: 3,
    realm: '阿修罗道',
    type: '善道',
    icon: '⚔',
    color: '#8b5cf6',
    description: '阿修罗道具有天道的福报但缺乏天道的德行，容易因嗔怒而堕落。',
    karmaRange: '70-85',
    previousLife: '人道或阿修罗道',
    specialCondition: '有武功或权势',
    enabled: true,
    usageCount: 345,
    successRate: 72.8,
    updateTime: '2023-12-14 16:45',
    detailedRules: ['业力值需达到70-85分', '前世为人道或阿修罗道', '具备武功或权势背景', '有一定的嗔怒习气', '通过战斗力测试'],
    restrictions: ['不得滥用武力', '不得欺压弱者', '需控制嗔怒情绪'],
    benefits: ['拥有强大战斗力', '享受权势地位', '寿命较长', '具备超人体能'],
    creator: '韦陀天王',
    lastModifier: '四大天王'
  },
  {
    id: 4,
    realm: '畜生道',
    type: '恶道',
    icon: '🐾',
    color: '#f97316',
    description: '畜生道缺乏智慧，难以自主修行，通常由业力牵引转世。',
    karmaRange: '20-59',
    previousLife: '不限',
    specialCondition: '业力偏向愚痴',
    enabled: true,
    usageCount: 1876,
    successRate: 92.1,
    updateTime: '2023-12-14 09:20',
    detailedRules: ['业力值为20-59分', '前世道别不限', '智慧明显不足', '有愚痴习气', '缺乏自主判断能力'],
    restrictions: ['智慧受限', '无法修行', '受本能驱使', '寿命较短'],
    benefits: ['免除复杂思考', '按本能生活', '某些种类可得人类喜爱'],
    creator: '地藏王菩萨',
    lastModifier: '地藏王菩萨'
  },
  {
    id: 5,
    realm: '饿鬼道',
    type: '恶道',
    icon: '👻',
    color: '#06b6d4',
    description: '饿鬼道长期处于饥渴状态，难以满足欲望，痛苦极大。',
    karmaRange: '10-39',
    previousLife: '不限',
    specialCondition: '贪欲过重',
    enabled: true,
    usageCount: 567,
    successRate: 88.9,
    updateTime: '2023-12-13 20:30',
    detailedRules: ['业力值为10-39分', '前世贪欲过重', '有吝啬或贪婪习气', '缺乏布施精神', '执着于物质享受'],
    restrictions: ['永远饥渴', '难以满足欲望', '受尽折磨', '寿命漫长'],
    benefits: ['无明显益处', '仅能通过受苦消除恶业'],
    creator: '地藏王菩萨',
    lastModifier: '地藏王菩萨'
  },
  {
    id: 6,
    realm: '地狱道',
    type: '恶道',
    icon: '🔥',
    color: '#ef4444',
    description: '地狱道是最痛苦的道别，需要受尽折磨消除恶业后方可转世。',
    karmaRange: '0-19',
    previousLife: '不限',
    specialCondition: '有重大恶业',
    enabled: true,
    usageCount: 234,
    successRate: 96.7,
    updateTime: '2023-12-13 15:10',
    detailedRules: ['业力值为0-19分', '前世有重大恶业', '犯有五逆重罪', '无悔改之心', '业力极其低下'],
    restrictions: ['受尽各种酷刑', '痛苦无法言喻', '无法逃脱', '时间漫长'],
    benefits: ['彻底消除恶业', '为将来转世做准备'],
    creator: '地藏王菩萨',
    lastModifier: '阎王爷'
  }
])

// 转世条件规则数据
const conditionRules = ref([
  {
    id: 1,
    name: '业力最低要求',
    category: '基础条件',
    description: '转世到特定道别需要满足的最低业力值要求',
    priority: '高',
    enabled: true,
    trigger: '业力值低于目标道别要求',
    action: '阻止转世并提示',
    scope: '所有道别',
    triggerCount: 1234,
    successRate: 98.5,
    detailDescription: '每个道别都有对应的业力最低要求，天道90分，人道60分，阿修罗道70分，畜生道20分，饿鬼道10分，地狱道0分',
    checkPoints: ['验证当前业力值', '对比目标道别要求', '生成转世报告'],
    exceptions: ['特殊功德加分', '紧急转世情况', '菩萨推荐'],
    creator: '阎王爷',
    createTime: '2023-01-01 00:00',
    lastModifier: '判官'
  },
  {
    id: 2,
    name: '前世债务清偿',
    category: '因果条件',
    description: '前世欠下的因果债务必须清偿完毕才能转世',
    priority: '高',
    enabled: true,
    trigger: '存在未了结的因果债务',
    action: '延迟转世直到债务清偿',
    scope: '善道转世',
    triggerCount: 567,
    successRate: 89.3,
    detailDescription: '包括情债、金钱债务、恩怨未了等各种因果关系，必须在转世前全部清算完毕',
    checkPoints: ['扫描因果档案', '查验债务记录', '确认清偿状态'],
    exceptions: ['债主主动免债', '通过功德抵偿', '特殊情况豁免'],
    creator: '孟婆',
    createTime: '2023-02-15 10:30',
    lastModifier: '黑白无常'
  },
  {
    id: 3,
    name: '修行成就验证',
    category: '特殊条件',
    description: '转世到天道需要验证修行成就和德行操守',
    priority: '中',
    enabled: true,
    trigger: '申请转世到天道',
    action: '进行修行成就考核',
    scope: '天道转世',
    triggerCount: 123,
    successRate: 76.8,
    detailDescription: '通过禅定测试、智慧考核、德行评估等多重验证，确保申请者具备天道所需的修行境界',
    checkPoints: ['禅定境界测试', '智慧水平评估', '德行操守审查', '神通能力验证'],
    exceptions: ['大菩萨推荐', '特殊功德豁免', '紧急度化需要'],
    creator: '观音菩萨',
    createTime: '2023-03-20 14:15',
    lastModifier: '文殊菩萨'
  },
  {
    id: 4,
    name: '恶业净化程度',
    category: '净化条件',
    description: '从恶道转世需要确保恶业净化程度达到标准',
    priority: '中',
    enabled: true,
    trigger: '从地狱道或饿鬼道转世',
    action: '检查恶业净化程度',
    scope: '恶道出离',
    triggerCount: 890,
    successRate: 92.1,
    detailDescription: '恶道众生需要通过受苦、忏悔、行善等方式净化恶业，达到一定标准后方可转世',
    checkPoints: ['恶业消除比例', '忏悔诚意评估', '善行累积情况', '受苦时间统计'],
    exceptions: ['遇到善知识指导', '发大愿心', '得到超度'],
    creator: '地藏王菩萨',
    createTime: '2023-04-10 09:00',
    lastModifier: '地藏王菩萨'
  },
  {
    id: 5,
    name: '家族业力传承',
    category: '血脉条件',
    description: '考虑家族业力传承对转世选择的影响',
    priority: '中',
    enabled: true,
    trigger: '申请转世到特定家族',
    action: '评估家族业力匹配度',
    scope: '人道转世',
    triggerCount: 445,
    successRate: 82.4,
    detailDescription: '家族成员之间存在业力共振，需要确保转世者业力与目标家族相匹配',
    checkPoints: ['家族业力历史', '血脉因果关系', '业力匹配度计算'],
    exceptions: ['因果报应需要', '特殊使命安排', '冤亲债主关系'],
    creator: '太乙真人',
    createTime: '2023-05-05 16:20',
    lastModifier: '太乙真人'
  },
  {
    id: 6,
    name: '地域环境适配',
    category: '环境条件',
    description: '确保转世地域环境与业力状态相适配',
    priority: '低',
    enabled: true,
    trigger: '选择转世地域',
    action: '匹配合适的地域环境',
    scope: '人道、畜生道',
    triggerCount: 2341,
    successRate: 94.7,
    detailDescription: '不同地域有不同的磁场和环境因素，需要与转世者的业力状态相匹配',
    checkPoints: ['地域磁场检测', '环境因素评估', '适配度计算'],
    exceptions: ['特殊任务需要', '因果关系驱动', '随缘安排'],
    creator: '土地公',
    createTime: '2023-06-12 11:45',
    lastModifier: '城隍爷'
  },
  {
    id: 7,
    name: '时间节点控制',
    category: '时机条件',
    description: '控制转世的时间节点，确保符合宇宙运行规律',
    priority: '低',
    enabled: true,
    trigger: '申请转世时间',
    action: '选择最佳转世时机',
    scope: '所有道别',
    triggerCount: 1567,
    successRate: 88.9,
    detailDescription: '考虑星象运行、季节变化、重大事件等因素，选择最适合的转世时机',
    checkPoints: ['星象位置计算', '时运分析', '大事件影响评估'],
    exceptions: ['紧急转世需要', '特殊使命时限', '业力成熟时机'],
    creator: '太白金星',
    createTime: '2023-07-08 08:30',
    lastModifier: '太白金星'
  },
  {
    id: 8,
    name: '修行伙伴匹配',
    category: '关系条件',
    description: '为修行者匹配合适的道侣、师傅、朋友等',
    priority: '低',
    enabled: false,
    trigger: '需要修行伙伴',
    action: '匹配合适的修行伙伴',
    scope: '善道转世',
    triggerCount: 234,
    successRate: 67.3,
    detailDescription: '通过业力匹配算法，为转世者安排有助于修行进步的人际关系',
    checkPoints: ['业力匹配度', '修行目标一致性', '因缘成熟度'],
    exceptions: ['独修行者', '特殊修行法门', '因果债务关系'],
    creator: '月老',
    createTime: '2023-08-15 19:20',
    lastModifier: '九天玄女'
  }
])

// 业力等级数据
const karmaLevels = ref([
  {
    id: 1,
    level: 'S',
    name: '圣者级',
    min: 95,
    max: 100,
    color: '#d4990a',
    realmAccess: ['天道'],
    description: '功德圆满的圣者级别'
  },
  {
    id: 2,
    level: 'A+',
    name: '大善级',
    min: 90,
    max: 94,
    color: '#52c41a',
    realmAccess: ['天道', '人道'],
    description: '大善之人，功德深厚'
  },
  {
    id: 3,
    level: 'A',
    name: '善人级',
    min: 80,
    max: 89,
    color: '#1890ff',
    realmAccess: ['天道', '人道', '阿修罗道'],
    description: '品德高尚的善人'
  },
  {
    id: 4,
    level: 'B',
    name: '良民级',
    min: 60,
    max: 79,
    color: '#722ed1',
    realmAccess: ['人道', '阿修罗道'],
    description: '品行端正的良民'
  },
  {
    id: 5,
    level: 'C',
    name: '普通级',
    min: 40,
    max: 59,
    color: '#fa8c16',
    realmAccess: ['人道', '畜生道'],
    description: '普通人的业力水平'
  },
  {
    id: 6,
    level: 'D',
    name: '罪民级',
    min: 20,
    max: 39,
    color: '#eb2f96',
    realmAccess: ['畜生道', '饿鬼道'],
    description: '有一定罪业的人'
  },
  {
    id: 7,
    level: 'E',
    name: '罪人级',
    min: 0,
    max: 19,
    color: '#f5222d',
    realmAccess: ['饿鬼道', '地狱道'],
    description: '罪业深重的恶人'
  }
])

// 特殊转世申请数据
const specialApplications = ref([
  {
    id: 1,
    applicantName: '张三',
    type: '紧急转世',
    reason: '因救助他人而意外身亡，申请提前转世到人道',
    currentKarma: 75,
    targetRealm: '人道',
    applicantRole: '义士',
    urgency: '紧急',
    status: 'pending',
    submitTime: '2023-12-15 10:30',
    reviewComment: '',
    previousLife: '宋朝将军',
    deathCause: '舍身救人',
    goodDeeds: ['救助落水儿童', '资助贫困学生', '参与抗洪救灾'],
    reviewer: '',
    processTime: '',
    attachments: ['见义勇为证明书', '英雄事迹报告', '民众联名推荐书']
  },
  {
    id: 2,
    applicantName: '李四',
    type: '特殊功德',
    reason: '毕生致力于慈善事业，申请转世到天道',
    currentKarma: 88,
    targetRealm: '天道',
    applicantRole: '慈善家',
    urgency: '普通',
    status: 'approved',
    submitTime: '2023-12-14 15:20',
    reviewComment: '功德确实，批准转世到天道',
    previousLife: '明朝商人',
    deathCause: '自然死亡',
    goodDeeds: ['建立孤儿院', '资助教育事业', '修建桥梁道路', '赈济灾民'],
    reviewer: '观音菩萨',
    processTime: '2023-12-14 16:30',
    attachments: ['慈善基金会证明', '受助者感谢信', '功德记录簿']
  },
  {
    id: 3,
    applicantName: '王五',
    type: '业力争议',
    reason: '对业力计算结果有异议，申请重新审核',
    currentKarma: 45,
    targetRealm: '人道',
    applicantRole: '文人',
    urgency: '普通',
    status: 'rejected',
    submitTime: '2023-12-13 09:15',
    reviewComment: '经审核，业力计算无误，维持原判',
    previousLife: '清朝书生',
    deathCause: '病故',
    goodDeeds: ['著书立说', '教育后人'],
    reviewer: '文曲星',
    processTime: '2023-12-13 14:20',
    attachments: ['学术成就证明', '弟子推荐信']
  },
  {
    id: 4,
    applicantName: '赵六',
    type: '菩萨推荐',
    reason: '地藏菩萨亲自推荐，申请从地狱道直接转世人道',
    currentKarma: 15,
    targetRealm: '人道',
    applicantRole: '悔罪者',
    urgency: '紧急',
    status: 'pending',
    submitTime: '2023-12-15 14:45',
    reviewComment: '',
    previousLife: '汉朝恶霸',
    deathCause: '天谴而死',
    goodDeeds: ['地狱中真心忏悔', '帮助其他恶鬼觉悟', '发愿度化众生'],
    reviewer: '',
    processTime: '',
    attachments: ['地藏菩萨推荐书', '忏悔记录', '觉悟证明']
  },
  {
    id: 5,
    applicantName: '钱七',
    type: '因果债务',
    reason: '前世欠债未还，债主已同意免除，申请正常转世',
    currentKarma: 52,
    targetRealm: '人道',
    applicantRole: '商人',
    urgency: '普通',
    status: 'approved',
    submitTime: '2023-12-12 11:20',
    reviewComment: '债务确已免除，同意转世',
    previousLife: '民国商人',
    deathCause: '心脏病',
    goodDeeds: ['诚信经营', '照顾员工家属'],
    reviewer: '孟婆',
    processTime: '2023-12-12 15:40',
    attachments: ['债务免除书', '商业诚信记录']
  },
  {
    id: 6,
    applicantName: '孙八',
    type: '修行成就',
    reason: '修行有成，申请跳级转世到阿修罗道',
    currentKarma: 65,
    targetRealm: '阿修罗道',
    applicantRole: '武僧',
    urgency: '普通',
    status: 'pending',
    submitTime: '2023-12-15 09:10',
    reviewComment: '',
    previousLife: '唐朝武僧',
    deathCause: '坐化圆寂',
    goodDeeds: ['降妖除魔', '保护寺院', '传授武艺', '济世救人'],
    reviewer: '',
    processTime: '',
    attachments: ['修行证明', '武功传承书', '师父推荐信']
  },
  {
    id: 7,
    applicantName: '周九',
    type: '特殊使命',
    reason: '受天庭指派，需转世执行特殊使命',
    currentKarma: 92,
    targetRealm: '人道',
    applicantRole: '天将',
    urgency: '机密',
    status: 'approved',
    submitTime: '2023-12-11 20:15',
    reviewComment: '天庭指派，特批通过',
    previousLife: '天界护法',
    deathCause: '任务完成',
    goodDeeds: ['保护凡间', '维护正义', '降妖除魔'],
    reviewer: '玉皇大帝',
    processTime: '2023-12-11 20:16',
    attachments: ['天庭委任书', '使命详情(机密)', '身份证明']
  },
  {
    id: 8,
    applicantName: '吴十',
    type: '冤屈申诉',
    reason: '生前遭受冤枉，已查明真相，申请补偿转世',
    currentKarma: 68,
    targetRealm: '人道',
    applicantRole: '冤屈者',
    urgency: '普通',
    status: 'approved',
    submitTime: '2023-12-10 16:30',
    reviewComment: '冤屈属实，给予补偿转世',
    previousLife: '明朝忠臣',
    deathCause: '被陷害处死',
    goodDeeds: ['忠君爱国', '清正廉洁', '为民请命'],
    reviewer: '包青天',
    processTime: '2023-12-11 10:20',
    attachments: ['冤案平反书', '历史证据', '补偿方案']
  },
  {
    id: 9,
    applicantName: '郑十一',
    type: '亲情牵挂',
    reason: '放心不下幼子，申请转世到同一家庭',
    currentKarma: 71,
    targetRealm: '人道',
    applicantRole: '慈母',
    urgency: '普通',
    status: 'pending',
    submitTime: '2023-12-15 13:20',
    reviewComment: '',
    previousLife: '现代母亲',
    deathCause: '车祸身亡',
    goodDeeds: ['悉心照料家庭', '志愿服务', '乐于助人'],
    reviewer: '',
    processTime: '',
    attachments: ['母子关系证明', '家庭情况说明', '社区推荐信']
  },
  {
    id: 10,
    applicantName: '何十二',
    type: '业力超标',
    reason: '业力超出人道范围，但愿意留在人道继续修行',
    currentKarma: 91,
    targetRealm: '人道',
    applicantRole: '修行者',
    urgency: '低',
    status: 'pending',
    submitTime: '2023-12-14 08:45',
    reviewComment: '',
    previousLife: '现代高僧',
    deathCause: '老衰圆寂',
    goodDeeds: ['弘法利生', '慈悲济世', '培养弟子', '著述传法'],
    reviewer: '',
    processTime: '',
    attachments: ['修行记录', '弟子证言', '佛法成就证明']
  }
])

// 业力等级表格列
const karmaColumns = [
  {
    title: '等级',
    dataIndex: 'level',
    key: 'level',
    width: 120
  },
  {
    title: '业力范围',
    dataIndex: 'range',
    key: 'range',
    width: 200
  },
  {
    title: '可转世道别',
    dataIndex: 'realmAccess',
    key: 'realmAccess'
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description'
  },
  {
    title: '操作',
    dataIndex: 'actions',
    key: 'actions',
    width: 120
  }
]

// 计算属性
const filteredSpecialApplications = computed(() => {
  if (!specialFilter.value) return specialApplications.value
  return specialApplications.value.filter((app) => app.status === specialFilter.value)
})

// 工具方法
const generateId = () => {
  return Date.now() + Math.random().toString(36).substr(2, 9)
}

const getCurrentTime = () => {
  return new Date().toLocaleString('zh-CN')
}

// 六道轮回规则方法
const addRealmRule = () => {
  editingRealmRule.value = {
    realm: '',
    type: '善道',
    icon: '',
    color: '#1890ff',
    description: '',
    karmaRange: '',
    previousLife: '',
    specialCondition: '',
    enabled: true,
    usageCount: 0,
    successRate: 0,
    detailedRules: [],
    restrictions: [],
    benefits: [],
    creator: '',
    lastModifier: ''
  }
  detailedRulesText.value = ''
  restrictionsText.value = ''
  benefitsText.value = ''
  showRealmRuleModal.value = true
}

const editRule = (rule) => {
  editingRealmRule.value = { ...rule }
  detailedRulesText.value = rule.detailedRules ? rule.detailedRules.join('\n') : ''
  restrictionsText.value = rule.restrictions ? rule.restrictions.join('\n') : ''
  benefitsText.value = rule.benefits ? rule.benefits.join('\n') : ''
  showRealmRuleModal.value = true
}

const saveRealmRule = () => {
  // 处理数组字段
  if (detailedRulesText.value.trim()) {
    editingRealmRule.value.detailedRules = detailedRulesText.value
      .trim()
      .split('\n')
      .filter((item) => item.trim())
  }
  if (restrictionsText.value.trim()) {
    editingRealmRule.value.restrictions = restrictionsText.value
      .trim()
      .split('\n')
      .filter((item) => item.trim())
  }
  if (benefitsText.value.trim()) {
    editingRealmRule.value.benefits = benefitsText.value
      .trim()
      .split('\n')
      .filter((item) => item.trim())
  }

  if (editingRealmRule.value.id) {
    // 编辑
    const index = realmRules.value.findIndex((rule) => rule.id === editingRealmRule.value.id)
    if (index !== -1) {
      editingRealmRule.value.updateTime = getCurrentTime()
      realmRules.value[index] = { ...editingRealmRule.value }
      message.success('规则更新成功')
    }
  } else {
    // 新增
    editingRealmRule.value.id = generateId()
    editingRealmRule.value.updateTime = getCurrentTime()
    realmRules.value.push({ ...editingRealmRule.value })
    message.success('规则添加成功')
  }

  showRealmRuleModal.value = false
}

const cancelRealmRule = () => {
  showRealmRuleModal.value = false
  editingRealmRule.value = {}
}

const copyRule = (rule) => {
  const newRule = {
    ...rule,
    id: generateId(),
    realm: rule.realm + '_副本',
    updateTime: getCurrentTime(),
    usageCount: 0
  }
  realmRules.value.push(newRule)
  message.success(`${rule.realm}规则已复制`)
}

const deleteRule = (rule) => {
  deleteTarget.value = {
    type: '规则',
    name: rule.realm,
    id: rule.id,
    category: 'realm'
  }
  showDeleteModal.value = true
}

const toggleRule = (rule) => {
  message.success(`${rule.realm}规则已${rule.enabled ? '启用' : '禁用'}`)
}

// 转世条件规则方法
const addCondition = () => {
  editingCondition.value = {
    name: '',
    category: '基础条件',
    description: '',
    priority: '中',
    enabled: true,
    trigger: '',
    action: '',
    scope: '',
    triggerCount: 0,
    successRate: 0,
    detailDescription: '',
    checkPoints: [],
    exceptions: [],
    creator: '',
    createTime: getCurrentTime(),
    lastModifier: ''
  }
  checkPointsText.value = ''
  exceptionsText.value = ''
  showConditionModal.value = true
}

const editCondition = (condition) => {
  editingCondition.value = { ...condition }
  checkPointsText.value = condition.checkPoints ? condition.checkPoints.join('\n') : ''
  exceptionsText.value = condition.exceptions ? condition.exceptions.join('\n') : ''
  showConditionModal.value = true
}

const saveCondition = () => {
  // 处理数组字段
  if (checkPointsText.value.trim()) {
    editingCondition.value.checkPoints = checkPointsText.value
      .trim()
      .split('\n')
      .filter((item) => item.trim())
  }
  if (exceptionsText.value.trim()) {
    editingCondition.value.exceptions = exceptionsText.value
      .trim()
      .split('\n')
      .filter((item) => item.trim())
  }

  if (editingCondition.value.id) {
    // 编辑
    const index = conditionRules.value.findIndex((condition) => condition.id === editingCondition.value.id)
    if (index !== -1) {
      editingCondition.value.lastModifier = editingCondition.value.creator || '系统管理员'
      conditionRules.value[index] = { ...editingCondition.value }
      message.success('条件更新成功')
    }
  } else {
    // 新增
    editingCondition.value.id = generateId()
    conditionRules.value.push({ ...editingCondition.value })
    message.success('条件添加成功')
  }

  showConditionModal.value = false
}

const cancelCondition = () => {
  showConditionModal.value = false
  editingCondition.value = {}
}

const deleteCondition = (condition) => {
  deleteTarget.value = {
    type: '条件',
    name: condition.name,
    id: condition.id,
    category: 'condition'
  }
  showDeleteModal.value = true
}

const testCondition = (condition) => {
  message.info(`测试条件：${condition.name}`)
}

// 业力等级方法
const addKarmaLevel = () => {
  editingKarma.value = {
    level: '',
    name: '',
    min: 0,
    max: 100,
    color: '#1890ff',
    realmAccess: [],
    description: ''
  }
  realmAccessText.value = ''
  showKarmaModal.value = true
}

const editKarmaLevel = (level) => {
  editingKarma.value = { ...level }
  realmAccessText.value = level.realmAccess ? level.realmAccess.join('\n') : ''
  showKarmaModal.value = true
}

const saveKarma = () => {
  // 处理数组字段
  if (realmAccessText.value.trim()) {
    editingKarma.value.realmAccess = realmAccessText.value
      .trim()
      .split('\n')
      .filter((item) => item.trim())
  }

  if (editingKarma.value.id) {
    // 编辑
    const index = karmaLevels.value.findIndex((level) => level.id === editingKarma.value.id)
    if (index !== -1) {
      karmaLevels.value[index] = { ...editingKarma.value }
      message.success('业力等级更新成功')
    }
  } else {
    // 新增
    editingKarma.value.id = generateId()
    karmaLevels.value.push({ ...editingKarma.value })
    message.success('业力等级添加成功')
  }

  showKarmaModal.value = false
}

const cancelKarma = () => {
  showKarmaModal.value = false
  editingKarma.value = {}
}

const deleteKarmaLevel = (level) => {
  deleteTarget.value = {
    type: '业力等级',
    name: level.name,
    id: level.id,
    category: 'karma'
  }
  showDeleteModal.value = true
}

// 特殊申请方法
const addSpecialApplication = () => {
  editingSpecial.value = {
    applicantName: '',
    type: '紧急转世',
    reason: '',
    currentKarma: 50,
    targetRealm: '人道',
    applicantRole: '',
    urgency: '普通',
    status: 'pending',
    submitTime: getCurrentTime(),
    reviewComment: '',
    previousLife: '',
    deathCause: '',
    goodDeeds: [],
    reviewer: '',
    processTime: '',
    attachments: []
  }
  goodDeedsText.value = ''
  attachmentsText.value = ''
  showSpecialModal.value = true
}

const editSpecialApplication = (application) => {
  editingSpecial.value = { ...application }
  goodDeedsText.value = application.goodDeeds ? application.goodDeeds.join('\n') : ''
  attachmentsText.value = application.attachments ? application.attachments.join('\n') : ''
  showSpecialModal.value = true
}

const saveSpecial = () => {
  // 处理数组字段
  if (goodDeedsText.value.trim()) {
    editingSpecial.value.goodDeeds = goodDeedsText.value
      .trim()
      .split('\n')
      .filter((item) => item.trim())
  }
  if (attachmentsText.value.trim()) {
    editingSpecial.value.attachments = attachmentsText.value
      .trim()
      .split('\n')
      .filter((item) => item.trim())
  }

  if (editingSpecial.value.id) {
    // 编辑
    const index = specialApplications.value.findIndex((app) => app.id === editingSpecial.value.id)
    if (index !== -1) {
      specialApplications.value[index] = { ...editingSpecial.value }
      message.success('申请更新成功')
    }
  } else {
    // 新增
    editingSpecial.value.id = generateId()
    specialApplications.value.push({ ...editingSpecial.value })
    message.success('申请添加成功')
  }

  showSpecialModal.value = false
}

const cancelSpecial = () => {
  showSpecialModal.value = false
  editingSpecial.value = {}
}

const deleteSpecialApplication = (application) => {
  deleteTarget.value = {
    type: '特殊申请',
    name: application.applicantName + ' - ' + application.type,
    id: application.id,
    category: 'special'
  }
  showDeleteModal.value = true
}

const approveApplication = (application) => {
  application.status = 'approved'
  application.reviewComment = '申请已批准'
  application.reviewer = '系统管理员'
  application.processTime = getCurrentTime()
  message.success(`${application.applicantName}的申请已批准`)
}

const rejectApplication = (application) => {
  application.status = 'rejected'
  application.reviewComment = '申请被拒绝'
  application.reviewer = '系统管理员'
  application.processTime = getCurrentTime()
  message.warning(`${application.applicantName}的申请已拒绝`)
}

const viewApplicationDetail = (application) => {
  editSpecialApplication(application)
}

// 删除确认方法
const confirmDelete = () => {
  const { category, id } = deleteTarget.value

  switch (category) {
    case 'realm':
      const realmIndex = realmRules.value.findIndex((rule) => rule.id === id)
      if (realmIndex !== -1) {
        realmRules.value.splice(realmIndex, 1)
        message.success('规则删除成功')
      }
      break
    case 'condition':
      const conditionIndex = conditionRules.value.findIndex((condition) => condition.id === id)
      if (conditionIndex !== -1) {
        conditionRules.value.splice(conditionIndex, 1)
        message.success('条件删除成功')
      }
      break
    case 'karma':
      const karmaIndex = karmaLevels.value.findIndex((level) => level.id === id)
      if (karmaIndex !== -1) {
        karmaLevels.value.splice(karmaIndex, 1)
        message.success('业力等级删除成功')
      }
      break
    case 'special':
      const specialIndex = specialApplications.value.findIndex((app) => app.id === id)
      if (specialIndex !== -1) {
        specialApplications.value.splice(specialIndex, 1)
        message.success('申请删除成功')
      }
      break
  }

  showDeleteModal.value = false
}

const cancelDelete = () => {
  showDeleteModal.value = false
  deleteTarget.value = { type: '', name: '', id: '', category: '' }
}

// 其他功能方法
const exportRules = () => {
  const data = {
    realmRules: realmRules.value,
    conditionRules: conditionRules.value,
    karmaLevels: karmaLevels.value,
    specialApplications: specialApplications.value,
    exportTime: getCurrentTime()
  }

  // 模拟导出
  console.log('导出数据:', data)
  message.success('规则导出成功')
}

const getRealmColor = (realm) => {
  const colors = {
    天道: 'gold',
    人道: 'green',
    阿修罗道: 'purple',
    畜生道: 'orange',
    饿鬼道: 'cyan',
    地狱道: 'red'
  }
  return colors[realm] || 'default'
}

const getStatusColor = (status) => {
  const colors = {
    pending: 'processing',
    approved: 'success',
    rejected: 'error'
  }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待审',
    approved: '已批准',
    rejected: '已拒绝'
  }
  return texts[status] || status
}

// 返回主页方法
const goBack = () => {
  router.push('/reincarnation')
}
</script>

<style lang="scss" scoped>
.rules-management {
  padding: 0;

  // 页面头部
  .page-header {
    margin-bottom: 32px;
    background: rgba(255, 255, 255, 0.03);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 12px;
    padding: 24px;

    .header-nav {
      margin-bottom: 24px;

      .nav-left {
        display: flex;
        align-items: center;
        gap: 24px;
      }

      .back-btn {
        color: $text-secondary;
        padding: 6px 12px;
        height: auto;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 6px;
        border-radius: 6px;
        transition: all 0.2s ease;

        &:hover {
          color: $primary-color;
          background: rgba(114, 46, 209, 0.1);
        }

        span {
          font-weight: 500;
        }
      }

      .breadcrumb {
        display: flex;
        align-items: center;
        font-size: 14px;
        margin: 0;

        .breadcrumb-item {
          display: flex;
          align-items: center;
          gap: 6px;
          color: $text-secondary;
          text-decoration: none;
          line-height: 14px;
          height: 14px;

          &:hover {
            color: $primary-color;
          }

          &.current {
            color: $text-primary;
            cursor: default;
          }

          span {
            line-height: 14px;
            height: 14px;
            display: flex;
            align-items: center;
          }
        }

        .breadcrumb-separator {
          color: $text-tertiary;
          margin: 0 8px;
          line-height: 14px;
          height: 14px;
          display: flex;
          align-items: center;
        }
      }
    }

    .header-content {
      display: flex;
      align-items: flex-end;
      justify-content: space-between;

      .header-main {
        .page-title {
          font-size: 28px;
          font-weight: 600;
          color: $text-primary;
          margin: 0 0 8px 0;
          line-height: 1.2;
        }

        .page-description {
          font-size: 14px;
          color: $text-secondary;
          margin: 0;
          line-height: 1.4;
        }
      }

      .header-actions {
        display: flex;
        gap: 12px;

        .ant-btn {
          height: 36px;
          padding: 0 16px;
          border-radius: 6px;
          font-size: 14px;
          transition: all 0.2s ease;

          &:hover {
            transform: translateY(-1px);
          }
        }
      }
    }
  }

  // 功能导航
  .function-nav {
    margin-bottom: 32px;

    .nav-card {
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid rgba(255, 255, 255, 0.1);
      border-radius: 16px;
      padding: 20px;
      cursor: pointer;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      height: 100px;

      &:hover,
      &.active {
        background: rgba(114, 46, 209, 0.1);
        border-color: $primary-color;
        transform: translateY(-2px);
      }

      .nav-icon {
        width: 60px;
        height: 60px;
        border-radius: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        color: white;
        margin-right: 20px;
        flex-shrink: 0;

        &.realms {
          background: linear-gradient(135deg, #f59e0b, #fbbf24);
        }

        &.conditions {
          background: linear-gradient(135deg, #722ed1, #9254de);
        }

        &.karma {
          background: linear-gradient(135deg, #13c2c2, #36cfc9);
        }

        &.special {
          background: linear-gradient(135deg, #eb2f96, #f759ab);
        }
      }

      .nav-content {
        flex: 1;

        .nav-title {
          font-size: 18px;
          font-weight: 600;
          color: $text-primary;
          margin-bottom: 6px;
        }

        .nav-count {
          font-size: 14px;
          color: $text-secondary;
        }
      }
    }
  }

  // 主要内容区域
  .main-content {
    .content-section {
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid rgba(255, 255, 255, 0.15);
      border-radius: 16px;
      padding: 24px;
      backdrop-filter: blur(10px);

      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
        padding-bottom: 16px;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);

        h3 {
          font-size: 20px;
          font-weight: 600;
          color: $text-primary;
          margin: 0;
        }
      }
    }
  }

  // 六道轮回规则网格
  .realm-rules-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 24px;

    .realm-rule-card {
      background: rgba(255, 255, 255, 0.03);
      border: 1px solid rgba(255, 255, 255, 0.08);
      border-radius: 12px;
      padding: 20px;
      transition: all 0.3s ease;

      &:hover {
        border-color: rgba(255, 255, 255, 0.2);
        transform: translateY(-2px);
      }

      .rule-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .realm-info {
          display: flex;
          align-items: center;

          .realm-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 20px;
            margin-right: 16px;
          }

          .realm-details {
            .realm-name {
              font-size: 18px;
              font-weight: 600;
              color: $text-primary;
              margin-bottom: 4px;
            }

            .realm-type {
              font-size: 12px;
              color: $text-secondary;
            }
          }
        }

        .rule-actions {
          display: flex;
          align-items: center;
          gap: 8px;
        }
      }

      .rule-content {
        margin-bottom: 16px;

        .rule-description {
          font-size: 14px;
          color: $text-secondary;
          line-height: 1.6;
          margin-bottom: 16px;
        }

        .rule-conditions {
          .condition-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 13px;

            .condition-label {
              color: $text-tertiary;
            }

            .condition-value {
              color: $text-primary;
              font-weight: 500;
            }
          }
        }
      }

      .rule-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 16px;
        border-top: 1px solid rgba(255, 255, 255, 0.05);

        .rule-stats {
          display: flex;
          gap: 16px;

          .stat-item {
            font-size: 12px;

            .stat-label {
              color: $text-tertiary;
            }

            .stat-value {
              color: $text-primary;
              font-weight: 600;

              &.success {
                color: #52c41a;
              }
            }
          }
        }

        .rule-time {
          font-size: 12px;
          color: $text-tertiary;
        }
      }
    }
  }

  // 条件列表
  .conditions-list {
    display: flex;
    flex-direction: column;
    gap: 16px;

    .condition-card {
      background: rgba(255, 255, 255, 0.03);
      border: 1px solid rgba(255, 255, 255, 0.08);
      border-radius: 12px;
      padding: 20px;

      .condition-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .condition-info {
          .condition-name {
            font-size: 16px;
            font-weight: 600;
            color: $text-primary;
            margin-bottom: 4px;
          }

          .condition-category {
            font-size: 12px;
            color: $text-secondary;
          }
        }

        .condition-actions {
          display: flex;
          align-items: center;
          gap: 12px;
        }
      }

      .condition-content {
        margin-bottom: 16px;

        .condition-description {
          font-size: 14px;
          color: $text-secondary;
          margin-bottom: 16px;
          line-height: 1.6;
        }

        .condition-details {
          .detail-row {
            display: flex;
            margin-bottom: 8px;
            font-size: 13px;

            .detail-label {
              color: $text-tertiary;
              width: 80px;
              flex-shrink: 0;
            }

            .detail-value {
              color: $text-primary;
              flex: 1;
            }
          }
        }
      }

      .condition-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 16px;
        border-top: 1px solid rgba(255, 255, 255, 0.05);

        .condition-stats {
          font-size: 12px;
          color: $text-tertiary;
        }

        .condition-actions {
          display: flex;
          gap: 8px;
        }
      }
    }
  }

  // 业力等级表格
  .karma-levels-table {
    :deep(.ant-table) {
      background: transparent;

      .ant-table-thead > tr > th {
        background: rgba(255, 255, 255, 0.05);
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        color: $text-primary;
      }

      .ant-table-tbody > tr > td {
        background: transparent;
        border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        color: $text-secondary;
      }

      .ant-table-tbody > tr:hover > td {
        background: rgba(114, 46, 209, 0.1) !important;
      }
    }

    .karma-level {
      display: flex;
      align-items: center;
      gap: 12px;

      .level-badge {
        width: 32px;
        height: 32px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: bold;
        font-size: 14px;
      }

      .level-name {
        font-weight: 500;
        color: $text-primary;
      }
    }

    .karma-range {
      .range-bar {
        width: 120px;
        height: 6px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 3px;
        overflow: hidden;
        margin-bottom: 4px;

        .range-fill {
          height: 100%;
          border-radius: 3px;
          transition: width 0.3s ease;
        }
      }

      .range-text {
        font-size: 12px;
        color: $text-secondary;
      }
    }

    .realm-access {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;
    }
  }

  // 特殊申请列表
  .special-applications-list {
    display: flex;
    flex-direction: column;
    gap: 16px;

    .application-card {
      background: rgba(255, 255, 255, 0.03);
      border: 1px solid rgba(255, 255, 255, 0.08);
      border-radius: 12px;
      padding: 20px;

      .application-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16px;

        .application-info {
          .applicant-name {
            font-size: 18px;
            font-weight: 600;
            color: $text-primary;
            margin-bottom: 4px;
          }

          .application-type {
            font-size: 12px;
            color: $text-secondary;
          }
        }

        .application-status {
          text-align: right;

          .application-time {
            font-size: 12px;
            color: $text-tertiary;
            margin-top: 4px;
          }
        }
      }

      .application-content {
        margin-bottom: 16px;

        .application-reason {
          font-size: 14px;
          color: $text-secondary;
          margin-bottom: 16px;
          line-height: 1.6;
        }

        .application-details {
          .detail-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 12px;
            margin-bottom: 16px;

            .detail-item {
              .detail-label {
                font-size: 12px;
                color: $text-tertiary;
                margin-right: 8px;
              }

              .detail-value {
                font-size: 12px;
                color: $text-primary;
                font-weight: 500;
              }
            }
          }
        }

        .review-comment {
          font-size: 13px;
          color: $text-secondary;
          background: rgba(255, 255, 255, 0.05);
          padding: 12px;
          border-radius: 8px;
          border-left: 3px solid $primary-color;
        }
      }

      .application-actions {
        padding-top: 16px;
        border-top: 1px solid rgba(255, 255, 255, 0.05);
      }
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .rules-management {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;
    }

    .function-nav .nav-card {
      height: auto;
      padding: 16px;

      .nav-icon {
        width: 48px;
        height: 48px;
        font-size: 20px;
        margin-right: 16px;
      }
    }

    .realm-rules-grid {
      grid-template-columns: 1fr;
    }
  }
}
</style>
